/*
 * Copyright 2011 The Rusted Roof, LLC.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package org.proteusframework.spi;

import org.proteusframework.api.IPlatformDelegate;
import org.proteusframework.api.IPluginRegistrar;
import org.proteusframework.api.base.AbstractPluginRegistrar;
import org.proteusframework.api.config.IConfigPropertyPrototype;
import org.proteusframework.api.model.IDisplayableName;

import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Base class that every plugin archetype must register itself under using Java's <code>ServiceLoader</code>
 * architecture.
 *
 * @author Tacoma Four
 */
public abstract class ProteusRegistrarFactory<T extends AbstractPluginRegistrar> extends ProteusPluginFactory
        implements IProteusRegistrarFactory
{
    private static final Logger logger = Logger.getLogger(ProteusRegistrarFactory.class.getCanonicalName());
    private Class<T> clazz;

    protected ProteusRegistrarFactory(IDisplayableName displayableName, Class<T> clazz)
    {
        super(displayableName, null);
        this.clazz = clazz;

        if (logger.isLoggable(Level.FINE))
        {
            logger.fine("Instantiating ProteusRegistrarFactory for type " + displayableName.toString());
        }
    }

    protected ProteusRegistrarFactory(IDisplayableName displayableName,
                                      List<IConfigPropertyPrototype> providerProperties)
    {
        super(displayableName, null, providerProperties);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public IPluginRegistrar createFactory(IPlatformDelegate delegate)
    {
        if (logger.isLoggable(Level.FINE))
            logger.fine("Creating Plugin Registrar");

        IPluginRegistrar pluginRegistrar = null;

        try
        {

            pluginRegistrar = clazz.newInstance();
            pluginRegistrar.setPlatformDelegate(delegate);

        } catch (InstantiationException e)
        {
            logger.severe("Unable to create plugin registrar " + dn.toString() + ": " + e.getMessage());
        } catch (IllegalAccessException e)
        {
            logger.severe("Unable to create plugin registrar " + dn.toString() + ": " + e.getMessage());
        }

        return pluginRegistrar;
    }
}
